import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

const routes = [{
  path: '/',
  redirect: '/home'
}, {
  path: '/home',
  name: 'Home',
  component: () => import('../views/home.vue'),
  meta: {
    ifShowTabBar: true
  },
  children: [{
    // 子路径/要么去掉 要么加上父级路由
    path: 'propup',
    name: 'MyPopup',
    component: () => import('../views/MyPopup.vue')
  }]
}, {
  path: '/topic',
  name: 'Topic',
  component: () => import('../views/Topic.vue'),
  meta: {
    ifShowTabBar: true
  }
}, {
  path: '/category',
  name: 'Category',
  component: () => import('../views/category.vue'),
  meta: {
    ifShowTabBar: true
  }
}, {
  path: '/cart',
  name: 'Cart',
  component: () => import('../views/cart.vue'),
  meta: {
    ifShowTabBar: true
  }
}, {
  path: '/user',
  name: 'User',
  component: () => import('../views/user.vue'),
  meta: {
    ifShowTabBar: true
  }
}, {
  path: '/productdetail',
  name: 'ProductDetail',
  component: () => import('../views/productDetail.vue')
}]

const router = new VueRouter({
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

// 路由拦截
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('yanxuanToken')
  // 进入购物车必须带有token
  if (to.path === '/cart') {
    if (token) {
      next()
    } else {
      // 没有token
      Vue.prototype.$toast('请先登录')
      setTimeout(() => {
        next('/user')
      }, 1000)
    }
    return
  }
  // 适配所有路由
  next()
})

export default router
